package com.group.hugedatabehind.controller;

import com.group.hugedatabehind.mapper.LoginMapper;
import com.group.hugedatabehind.pojo.User;
import com.group.hugedatabehind.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS})
public class LoginController {
    @Autowired
    private LoginMapper loginMapper;

//    @GetMapping("/getuser")
//    public List<User> getUser(){
//        List<User> userlist = loginMapper.getUser();
//        return userlist;
//    }
//
//    @PostMapping("/login")
//    public User login(@RequestBody User userfront){
//       User login = loginMapper.getOneUser(userfront);
//       return login;
//
//    }


//    @PostMapping("/login")
//    //Map类型
//    public String login(@RequestBody User userfront){
//        User login = loginMapper.getOneUser(userfront);
//        if (login != null){
//            //jwt令牌分为三部分，一般把数据放在第二部分（载荷）
//            Map<String, Object> map = new HashMap<>();
//            map.put("username", login.getUsername());
//            map.put("password", login.getPassword());
//            String jwt = JwtUtils.generateToken(map);
//            return jwt;
//        }else {
//            return "用户名或密码错误";
//        }


    //这里改成了map类型
    @PostMapping("/login")
    public Map<String,Object> login(@RequestBody User userFront){
        User loginUser = loginMapper.getOneUser(userFront);
        if (loginUser == null) {
            // 也可以抛业务异常，让全局异常处理器 return 统一格式
            throw new RuntimeException("用户名或密码错误");
        }
        Map<String, Object> payload = new HashMap<>();
        payload.put("username", loginUser.getUsername());
        payload.put("password", loginUser.getPassword());
        String jwt = JwtUtils.generateToken(payload);

        Map<String,Object> ret = new HashMap<>();
        ret.put("code", 0);
        ret.put("token", jwt);
        return ret;
    }

}
